(function () {

    "use strict";

    var api = {
        cashoutMoney: '/api/cash/cashout',
        userInfoUrl: '/api/user/userInfo'
    };

    sm.controller('wx-center-cash-out-controller', ['$scope', '$http', 'Toast', function ($scope, $http, Toast){

        $scope.money = '';
        $scope.cloudClick = false;
        $scope.showError = false;
        $scope.errorMsg = '';
        $scope.userInfo = {};

        $scope.$watch('money', function (newValue, oldValue) {
            if (newValue === oldValue) {
                return false;
            }

            if (!$scope.userInfo) {
                return false;
            }

            var iptAmount = parseInt(newValue * 100);
            var userAmount = $scope.userInfo.amountUnLimit;

            if (iptAmount > userAmount) {
                $scope.couldClick = false;
                setError(true, '金额超过可提现金额');
                return false;
            }

            $scope.cloudClick = iptAmount >= 100 && iptAmount <= userAmount;
            if ($scope.cloudClick) {
                setError(false, '');
            } else if (iptAmount == 0) {
                setError(false, '')
            } else {
                setError(true, '请检查可用金额是否满足要求');
            }
        });

        /**
         * @param show
         * @param msg
         */
        function setError(show, msg) {
            $scope.showError = show;
            $scope.errorMsg = msg;
        }

        $scope.getUserInfo = function () {
            $http.get(api.userInfoUrl).success(function (res) {
                if (res.state) {
                    $scope.userInfo = res.data;
                } else {
                    $scope.showError = true;
                    $scope.errorMsg = '无法拉取用户余额信息';
                }
            });
        };

        $scope.getUserInfo();

        /**
         * 提交
         * @returns {boolean}
         */
        $scope.submit = function () {

            var money = parseInt($scope.money * 100);
            if (!$scope.cloudClick || money < 100) {
                return false;
            }

            if (money > $scope.userInfo.amountUnLimit) {
                $scope.showError = true;
                $scope.errorMsg = '可提现金额不足';
                $scope.couldClick = false;
                return false;
            }

            $scope.cloudClick = false;
            Toast.loading({'title': '请等待...'});
            $http.post(api.cashoutMoney, {
                amount: money
            }).success(function (res) {
                Toast.stop();
                if (res.state) {
                    location.href='/center/cashoutSucc';
                } else {
                    $scope.showError = true;
                    $scope.errorMsg = !res.error ? res.error : '提现申请失败';
                }
            });
        };

    }]);
})();

